/*
 * @Description: 流程定义数据表*核心表
 * @Author: DHL
 * @Date: 2022-08-26 10:30:29
 * @LastEditors: DHL
 * @LastEditTime: 2023-03-09 11:20:58
 */

import { defineComponent, computed, reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '@/types/table.d'
import usePermission from '@/hooks/web/permission'
import { ActReProcdefModel, ActReProcdefPageParams } from '@/api/flow/model/actReProcdefModel'
import {
  apiActReProcdefDeleteById,
  apiActReProcdefSearch,
  apiActReProcdefActivate,
  apiActReProcdefSuspend
} from '@/api/flow/actReProcdef'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import flowCategoryTree from '../components/flowCategoryTree.vue'
import actReProcdefForm from './form.vue'

export default defineComponent({
  name: 'ActReProcdef',
  components: { Splitpanes, Pane, flowCategoryTree, actReProcdefForm },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    // 权限控制
    const { hasPermission } = usePermission()

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 公共
     */
    const state = reactive({})

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<ActReProcdefModel> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      queryLikeStr: '', // 模糊查询关键字
      id: null, // 主键
      rev: null, // 版本号
      category: null, // 分类
      name: null, // 名称
      key: null, // 标识
      version: null, // 版本
      deploymentId: null, // 部署ID
      resourceName: null, // 资源名称
      dgrmResourceName: null, // 图片资源名称
      description: null, // 描述
      hasStartFormKey: null, // 拥有开始表单标识
      hasGraphicalNotation: null, // 拥有图形信息
      suspensionState: null, // 挂起状态【暂停状态 1激活 2暂停】
      tenantId: null, // 租户ID
      engineVersion: null, //
      derivedFrom: null, //
      derivedFromRoot: null, //
      derivedVersion: null, //
      latestVersion: true, // 最新版本
      active: false, // 激活的
      suspended: false // 暂停的
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: 'actReProcdefTable',
      sortConfig: {
        defaultSort: [{ field: 't.key_', order: 'desc' }]
      },
      columns: [
        { type: 'checkbox', fixed: 'left', title: '', align: 'center', width: 40 },
        { type: 'seq', fixed: 'left', title: '序号', width: 50 },
        { field: 'name', title: '名称', sortable: true },
        { field: 'key', title: '标识', sortable: true },
        { field: 'categoryName', title: '分类', sortable: true },
        { field: 'version', title: '版本', sortable: true },
        {
          field: 'suspensionState',
          title: '状态',
          sortable: true,
          params: { dict: 'FLOW_SUSPENSION_STATE' }
        },
        { field: 'description', title: '描述', sortable: true },
        { title: '操作', fixed: 'right', width: 160, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({
      cellDblclick(params: { row: ActReProcdefModel }) {
        if (hasPermission('ACT-RE-PROCDEF-VIEW')) {
          handleOpenForm('view', params.row)
        } else {
          ElMessage.warning('无权限访问')
        }
      }
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: ActReProcdefPageParams) {
      loading.value = true
      apiActReProcdefSearch(assign(queryParams, searchForm, { category: selectTreeNode.code }))
        .then((result) => {
          tableData.value = result
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 激活
     * @param row
     */
    function handleActivate(row: ActReProcdefModel) {
      loading.value = true

      apiActReProcdefActivate(row.id)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleRefresh()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 挂起
     * @param row
     */
    function handleSuspend(row: ActReProcdefModel) {
      loading.value = true

      apiActReProcdefSuspend(row.id)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleRefresh()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .finally(() => {
          loading.value = false
        })
    }

    //////////////////////////////////////////////////
    // 流程删除
    //////////////////////////////////////////////////
    const delDialogVisible = ref(false)
    const cascade = ref(false)
    let deleteRow: Nullable<ActReProcdefModel> = null

    /**
     * 删除流程实例
     */
    function handleDelete(row: ActReProcdefModel) {
      delDialogVisible.value = true
      deleteRow = row
    }

    /**
     * 确认删除
     */
    function handleDeleteSubmit() {
      if (!deleteRow) {
        ElMessage.warning('请选择一条数据删除')
        return
      }

      loading.value = true
      apiActReProcdefDeleteById(deleteRow.id, cascade.value)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleRefresh()
            delDialogVisible.value = false
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    //////////////////////////////////////////////////
    // 流程类别树
    //////////////////////////////////////////////////
    const flowCategoryTreeRef = ref()

    /**
     * 选中的树节点
     */
    let selectTreeNode: any = {}

    /**
     * 节点点击事件
     */
    function handleNodeClick(treeNode?: Node) {
      selectTreeNode = treeNode ? treeNode : {}
      handleSearch()
    }

    /**
     * 树刷新
     */
    function handleTreeSearch() {}

    //////////////////////////////////////////////////
    // 弹框查看详情
    //////////////////////////////////////////////////
    /**
     * 弹出表单
     */
    function handleOpenForm(action: string, row?: any) {
      formRef.value.handleOpen(action, row)
    }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => {})

    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      state,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      flowCategoryTreeRef,
      handleNodeClick,
      handleTreeSearch,
      handleActivate,
      handleSuspend,
      delDialogVisible,
      handleDeleteSubmit,
      cascade
    }
  }
})
